package com.lovo.controller;

import com.alibaba.fastjson.JSON;
import com.lovo.dao.IPayDao;
import com.lovo.entity.PayEntity;
import com.lovo.util.CreateToken;
import com.lovo.util.Verifier;
import com.lovo.vo.ConsumeVO;
import com.lovo.vo.TopUpVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("pay")
@Api(tags = "充值、支付，支付结果监听payQueueResult队列 tag 0-支付成功 1-支付失败 2-余额不足")
public class PayController {
    @Autowired
    IPayDao payDao;
    @Autowired
    RedisTemplate redisTemplate;
    @ApiOperation(value = "根据用户编号和充值金额生成token")
    @GetMapping("tokenInfo/{userCode}/{money}")
    public String tokenInfo(@PathVariable("userCode") String userCode,
                            @PathVariable("money") double money){
         return CreateToken.createPayToken(userCode,money);
    }
    @ApiOperation(value = "充值，传入充值token,key=pay")
    @PostMapping("TopUp")
    public TopUpVO TopUp(HttpServletRequest request){
        TopUpVO vo=new TopUpVO();
        String token=   request.getHeader("pay");
        try {
            vo=    Verifier.verifierPayJwt(token);
            //充值保存
            PayEntity pay=      payDao.findDistinctFirstByUserCode(vo.getUserCode());
            if(null==pay){
                pay=new PayEntity();
                pay.setUserCode(vo.getUserCode());
                pay.setCurrentMoney(0);
            }
            double money=pay.getCurrentMoney()+vo.getMoney();//充值后的金额
            pay.setCurrentMoney(money);
            //重新写回VO
            vo.setUserCode(vo.getUserCode());
            vo.setMoney(vo.getMoney());
            vo.setCurrentMoney(money);
            vo.setTag(0);
            //持久化
            payDao.save(pay);
        }catch (Exception e){
            //失败2
            vo.setTag(1);
        }
        return  vo;
    }


    @ApiOperation(value = "消费：用户code，消费金额，消费明细")
    @GetMapping("consume/{userCode}/{consumeMoney}/{goodsInfo}")
    @Transactional
    public boolean consumption(@PathVariable("userCode") String userCode,
                            @PathVariable("consumeMoney") float consumeMoney,
                            @PathVariable("goodsInfo") String goodsInfo){
        ConsumeVO vo=new ConsumeVO();
        vo.setUserCode(userCode);
        vo.setConsumeMoney(consumeMoney);
        vo.setUserJson(goodsInfo);

        //获取用户当前金额
        PayEntity pay = payDao.findDistinctFirstByUserCode(vo.getUserCode());
        if(null!=pay) {
            double currentMoney = pay.getCurrentMoney();//当前金额
            if (vo.getConsumeMoney() > currentMoney) {
                //超支
                vo.setTag(2);
            } else {
                //正常
                vo.setTag(0);
                //消费
                currentMoney=currentMoney-vo.getConsumeMoney();
                pay.setCurrentMoney(currentMoney);
                vo.setCurrentMoney(currentMoney);
                pay=   payDao.save(pay);
                //放入redis

                vo.setUserCode(pay.getUserCode());
                vo.setUserJson(goodsInfo);
                vo.setConsumeMoney(vo.getConsumeMoney());
                vo.setCurrentMoney(pay.getCurrentMoney());
              String consumeJson=  JSON.toJSONString(vo);
             redisTemplate.opsForList().rightPush(vo.getUserCode(),consumeJson);
            }
        }else {
            vo.setTag(1);
            return false;
        }
       return  true;
    }

    @ApiOperation("获取支付结果-tag=0 正常 1-失败 2-超支")
    @GetMapping("consumeConfirm/{userCode}")
    public Object consumeConfirm(@PathVariable("userCode")String userCode){
     return    redisTemplate.opsForList().leftPop(userCode,5, TimeUnit.SECONDS);
    }

}
